const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 封装POST请求
const post = (url, data) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      method: 'POST',
      data: data,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(new Error(`HTTP错误: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', err);
        reject(new Error('网络错误，请稍后再试'));
      }
    });
  });
}

// 页面跳转工具
const goPage = (url, params = {}, isTab = false) => {
  if (isTab) {
    wx.switchTab({
      url: url
    });
  } else {
    wx.navigateTo({
      url: url
    });
  }
}

// Toast提示工具
const showToast = {
  success: (title) => {
    wx.showToast({
      title: title,
      icon: 'success'
    });
  },
  error: (title) => {
    wx.showToast({
      title: title,
      icon: 'error'
    });
  },
  none: (title) => {
    wx.showToast({
      title: title,
      icon: 'none'
    });
  }
}

module.exports = {
  formatTime,
  post,
  goPage,
  showToast
}
